package com.huxiu.yd;

import com.huxiu.yd.net.NetUtils;
import com.huxiu.yd.net.NetworkConstants;
import com.huxiu.yd.net.model.Category;
import com.huxiu.yd.utils.Utils;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by yao on 15/8/23:下午11:26.
 */
public class PublishSpareActivity2 extends BaseActivity implements View.OnClickListener {

    @InjectView(R.id.back)
    ImageView back;

    @InjectView(R.id.title)
    TextView title;

    @InjectView(R.id.title_edit)
    EditText titleEdit;

    @InjectView(R.id.desc_edit)
    EditText descEdit;

    @InjectView(R.id.area_selector)
    TextView areaSelector;

    @InjectView(R.id.mobile)
    EditText mobile;

    @InjectView(R.id.contact_person)
    EditText contactPerson;

    @InjectView(R.id.publish_button)
    TextView publishButton;
    @InjectView(R.id.contact_panel)
    LinearLayout contactPanel;
    @InjectView(R.id.contact_method)
    TextView contactMethod;

    private Category category, company, product;

    private boolean isUsed;

    private int quality;

    private String price;

    private List<Bitmap> images = new ArrayList<>();

    public int contact_method = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_spare2);
        ButterKnife.inject(this);
        back.setOnClickListener(this);
        areaSelector.setOnClickListener(this);
        publishButton.setOnClickListener(this);
        contactMethod.setOnClickListener(this);
        title.setText(R.string.publish_spare_item);
        Intent intent = getIntent();
        category = (Category) intent.getSerializableExtra("category");
        company = (Category) intent.getSerializableExtra("company");
        product = (Category) intent.getSerializableExtra("product");
        isUsed = intent.getBooleanExtra("used", false);
        quality = intent.getIntExtra("quality", 0);
        if (quality == 10) {
            quality = 0;
        }
        price = intent.getStringExtra("price");
        images = PublishSpareActivity.images;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.area_selector:
                startActivityForResult(new Intent(this, SelectAreaActivity.class), 0);
                break;
            case R.id.publish_button:
                if (isInputValid()) {
                    publishSpare();
                }
                break;
            case R.id.contact_method: {
                new AlertDialog.Builder(this)
                        .setItems(new String[]{"电话联系", "私信"}, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                contact_method = which;
                                switch (which) {
                                    case 0:
                                        contactPanel.setVisibility(View.VISIBLE);
                                        contactMethod.setText("电话联系");
                                        contactMethod.setTextColor(getResources().getColor(R
                                                .color.dark_text));
                                        break;
                                    case 1:
                                        contactPanel.setVisibility(View.GONE);
                                        contactMethod.setText("私信");
                                        contactMethod.setTextColor(getResources().getColor(R.color.dark_text));
                                        break;
                                }
                            }
                        })
                        .setNegativeButton(android.R.string.cancel, null)
                        .show();
            }
            break;
        }
    }

    private void publishSpare() {
        String url = NetworkConstants.GOODS_URL + "?act=add_goods";
        Map<String, String> params = new HashMap<>();
//        params.put("act", "add_goods");
        params.put("title", titleEdit.getText().toString());
        params.put("description", descEdit.getText().toString());
        params.put("category_id", category.id);
        params.put("company_id", company.id);
        params.put("product_id", product.product_id);
        params.put("is_use", isUsed ? "1" : "0");
        params.put("depreciation", Integer.toString(quality));
        params.put("sale_price", price);
        params.put("province_id", provinceId);
        params.put("city_id", cityId);
        if (contact_method == 0)
            params.put("mobile", mobile.getText().toString());
        params.put("contact_name", contactPerson.getText().toString());
//        GsonRequest<BaseResponse> request = new GsonRequest<>(url, Method.POST, BaseResponse.class,
//                true, params, new Listener<BaseResponse>() {
//            @Override
//            public void onResponse(BaseResponse response) {
//                dismissProgress();
//                if (response.isSuccess()) {
//                    Utils.showToast(R.string.publish_spare_item_success);
//                    setResult(RESULT_OK);
//                    finish();
//                }
//            }
//        }, mErrorListener);
//        Map<String, Bitmap> parts = new HashMap<>();
//        for (int i = 0; i < images.size(); i++) {
//            parts.put("pic_" + (i + 1), images.get(i));
//        }
//        request.setMultiPart(parts);
//        mQueue.add(request);
//        mQueue.start();
        params.putAll(NetUtils.GetCommonMap(this, true));
        final NetUtils utils = new NetUtils(this, params, url);
        for (int i = 0; i < images.size(); i++) {
            utils.setImageEntities("pic_" + (i + 1), images.get(i));
        }
        new Thread() {
            @Override
            public void run() {
                super.run();
                final String result = utils.uploadMultiPart();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissProgress();
                        try {
                            JSONObject object = new JSONObject(result);
                            if (object.optInt("result", 0) == 1) {
                                Utils.showToast(R.string.publish_spare_item_success);
                                setResult(RESULT_OK);
                                finish();
                            } else {
                                Utils.showToast(object.getString("msg"));
                            }
                        } catch (Exception ignored) {

                        }
                    }
                });
            }
        }.start();
        showProgress();
    }

    private boolean isInputValid() {
        if (TextUtils.isEmpty(titleEdit.getText().toString())) {
            Utils.showToast(R.string.pls_input_spare_title);
            return false;
        }
        if (TextUtils.isEmpty(descEdit.getText().toString())) {
            Utils.showToast(R.string.pls_input_spare_desc);
            return false;
        }
        if (TextUtils.isEmpty(provinceId) || TextUtils.isEmpty(cityId)) {
            Utils.showToast(R.string.please_select_area);
            return false;
        }

        if (contact_method < 0) {
            Utils.showToast(getString(R.string.please_choose_input_method));
            return false;
        } else if (contact_method == 0) {
            if (TextUtils.isEmpty(mobile.getText().toString())) {
                Utils.showToast(R.string.please_input_mobile);
                return false;
            }
            if (TextUtils.isEmpty(contactPerson.getText().toString())) {
                Utils.showToast(R.string.pls_input_contact_person);
                return false;
            }
        }
        return true;
    }

    private String provinceId;

    private String cityId;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case 0:
                provinceId = data.getStringExtra("province_id");
                cityId = data.getStringExtra("city_id");
                areaSelector.setText(data.getStringExtra("province_name") + " " + data
                        .getStringExtra("city_name"));
                areaSelector.setTextColor(getResources().getColor(R
                        .color.dark_text));
                break;
        }
    }


}
